from PyQt5 import QtWidgets, QtGui, QtCore, sip
import YqRequest
import YqConfig


def set_font():
    font = QtGui.QFont()
    font.setFamily("微软雅黑")
    font.setPointSize(12)
    return font


'''
知识库实体
'''


class YqRepo:
    def __init__(self):
        # 知识库信息
        self.repo_info = {}
        # 已选中的
        self.selected_radio = {}
        # 多选框实体-知识库列表
        self.repo_radios = []
        self.font = set_font()
        # 请求实体
        self.YqRequest = None

    # 获取所有知识库名称及id
    def get_repo(self, ui, yq_config: YqConfig):
        usernmame = ui.lineEdit_namespace.text()
        token = ui.lineEdit_token.text()
        if usernmame == "" or token == "":
            raise Exception("请输入命名空间以及Token值")
        yq_config.username = usernmame
        yq_config.token = token
        yq_config.save_config()

        self.YqRequest = YqRequest.YqRequest(usernmame, token)
        # 发送请求-获取所有知识库
        get_repo_url = f"/users/{usernmame}/repos"
        result = self.YqRequest.do_get(get_repo_url)
        self.repo_info = {}
        for repo in result.get("data"):
            repo_id = str(repo["id"])
            repo_name = repo["name"]
            self.repo_info[repo_name] = repo_id
        self.set_repo(ui)

    # 设置知识库列表到多选框
    def set_repo(self, ui):
        for i in range(len(self.repo_radios)):
            sip.delete(self.repo_radios[i])
        self.repo_radios = []
        idx = 0
        for repo_name, repo_id in self.repo_info.items():
            radio_button = QtWidgets.QRadioButton(ui.layoutWidget1)

            radio_button.setObjectName(repo_id)
            radio_button.setText(repo_name)
            radio_button.setFont(self.font)
            self.repo_radios.append(radio_button)
            ui.gridLayout_repo.addWidget(radio_button, 0, idx + 1, 1, 1)
            # ui.horizontalLayout_repo.addWidget(radio_button, idx + 1, 0, 1, 1)
            idx += 1
            radio_button.toggled.connect(lambda: self.select_repo(self.repo_radios))

    # 选择知识库事件
    def select_repo(self, cbw):
        self.selected_radio = {}
        for i in range(len(cbw)):
            if cbw[i].isChecked():
                self.selected_radio[cbw[i].objectName()] = cbw[i].text()
